package com.wenqiner.requesttool.util;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RSAUtil {

    /**
     * 加密算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";

    /** 算法名称 - SHA256withRSA */
    public static final String ALGORITHM_SHA256WITHRSA = "SHA256withRSA";
    /**
     * 获取公钥的key
     */
    private static final String PUBLIC_KEY = "RSAPublicKey";

    /**
     * 获取私钥的key
     */
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * <p>
     * 生成密钥对(公钥和私钥)
     * </p>
     *
     * @return map
     * @throws Exception e
     */
    public static Map<String, Object> genKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(2048);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    /*public static void main(String[] args) throws Exception {
        Map<String, Object> map = genKeyPair();
        String privateKey = getPrivateKey(map);
        System.out.println("privateKey:");
        System.out.println(privateKey);
        System.out.println("public:");
        System.out.println(getPublicKey(map));
    }*/


    /**
     * 公钥解密
     *
     * @return str
     * @throws Exception e
     */
    public static String decryptByPublicKey(String publicKeyText, String text) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64Decoder.decode(publicKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(Base64Decoder.decode(text));
        return new String(result);
    }

    /**
     * 私钥加密
     *
     * @return str
     * @throws Exception e
     */
    public static String encryptByPrivateKey(String privateKeyText, String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64Encoder.encode(privateKeyText).getBytes());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64Encoder.encode(result);
    }

    /**
     * 公钥加密
     *
     * @return str
     */
    public static String encryptByPublicKey(String publicKeyText, String text) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64Decoder.decode(publicKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64Encoder.encode(result);
    }

    /**
     * 私钥解密
     *
     * @return str
     * @throws Exception e
     */
    public static String decryptByPrivateKey(String privateKeyText, String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64Decoder.decode(privateKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(Base64Decoder.decode(text));
        return new String(result);
    }


    /**
     * <p>
     * 获取私钥
     * </p>
     *
     * @param keyMap 密钥对
     * @return str
     * @throws Exception e
     */
    public static String getPrivateKey(Map<String, Object> keyMap)
            throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return encode(key.getEncoded());
    }

    /**
     * <p>
     * 获取公钥
     * </p>
     *
     * @param keyMap 密钥对
     * @return str
     */
    public static String getPublicKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return encode(key.getEncoded());
    }

    /**
     * 二进制数据编码为BASE64字符串
     *
     * @param bytes byte[]
     * @return str
     */
    public static String encode(byte[] bytes) {
        return new String(java.util.Base64.getEncoder().encode(bytes));
    }

    /**
     * get base64 encoded signature which signed by private key
     *
     */
    public static String sign(String base64EncodedPrivateKey, String plainText) throws Exception {
        byte[] privateKey = java.util.Base64.getDecoder().decode(base64EncodedPrivateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
        KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey priKey = factory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance(ALGORITHM_SHA256WITHRSA);
        signature.initSign(priKey);
        signature.update(plainText.getBytes(StandardCharsets.UTF_8));
        byte[] sign = signature.sign();
        return java.util.Base64.getEncoder().encodeToString(sign);
    }

    /**
     * <pre>
     * RSA256 verify sign
     * </pre>
     *
     * @param data                   UTF-8 data bytes
     * @param base64EncodedPublicKey public key
     * @param sign                   signature
     */
    public static boolean verifySign(byte[] data, String base64EncodedPublicKey, String sign) throws Exception {
        byte[] publicKey = java.util.Base64.getDecoder().decode(base64EncodedPublicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey pubKey = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(ALGORITHM_SHA256WITHRSA);
        signature.initVerify(pubKey);
        signature.update(data);
        return signature.verify(java.util.Base64.getDecoder().decode(sign));
    }
}
